import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import './ImageCaptcha.css';

const ImageCaptcha = ({ onValidate, error }) => {
  const { t } = useTranslation();
  const [targetItem, setTargetItem] = useState('');
  const [targetCategory, setTargetCategory] = useState('');
  const [options, setOptions] = useState([]);
  const [selectedOptions, setSelectedOptions] = useState([]);
  const [isVerified, setIsVerified] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [showFeedback, setShowFeedback] = useState(false);

  // Item categories for captcha
  const itemCategories = {
    animals: ['🐱', '🐶', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔', '🐧', '🐦'],
    fruits: ['🍎', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🍒', '🍑', '🥭', '🍍', '🥥', '🥝', '🍅', '🍆', '🥑', '🥦', '🥬'],
    vehicles: ['🚗', '🚕', '🚙', '🚌', '🚎', '🏎️', '🚓', '🚑', '🚒', '🚐', '🚚', '🚛', '🚜', '🏍️', '🚲', '🛵', '🚁', '✈️'],
    sports: ['⚽', '🏀', '🏈', '⚾', '🥎', '🎾', '🏐', '🏉', '🥏', '🎱', '🪀', '🏓', '🏸', '🏒', '🏑', '🥍', '🏏', '🪙'],
    food: ['🍕', '🍔', '🍟', '🌭', '🍿', '🥨', '🥐', '🍞', '🥖', '🧀', '🥚', '🍳', '🧈', '🥞', '🧇', '🥓', '🥩', '🍗'],
    nature: ['🌳', '🌲', '🌴', '🌵', '🌾', '🌿', '☘️', '🍀', '🍁', '🍂', '🍃', '🌱', '🌻', '🌹', '🏵️', '🌸', '💐', '🌷']
  };

  const categoryNames = {
    animals: { zh: '动物', en: 'animals' },
    fruits: { zh: '水果', en: 'fruits' },
    vehicles: { zh: '交通工具', en: 'vehicles' },
    sports: { zh: '运动', en: 'sports' },
    food: { zh: '食物', en: 'food' },
    nature: { zh: '自然', en: 'nature' }
  };

  // Generate new captcha challenge
  const generateCaptcha = () => {
    setIsRefreshing(true);
    setShowFeedback(false);
    
    setTimeout(() => {
      const categories = Object.keys(itemCategories);
      const randomCategory = categories[Math.floor(Math.random() * categories.length)];
      const items = itemCategories[randomCategory];
      
      setTargetCategory(randomCategory);
      
      // Create options array with more items (3x3 grid = 9 items)
      const newOptions = [];
      const targetItemsCount = 2 + Math.floor(Math.random() * 2); // 2-3 target items
      
      // Add target items
      for (let i = 0; i < targetItemsCount; i++) {
        const target = items[Math.floor(Math.random() * items.length)];
        if (!newOptions.includes(target)) {
          newOptions.push(target);
        }
      }
      
      // Fill the rest with random items from other categories
      while (newOptions.length < 9) {
        const otherCategory = categories[Math.floor(Math.random() * categories.length)];
        const otherItems = itemCategories[otherCategory];
        const randomItem = otherItems[Math.floor(Math.random() * otherItems.length)];
        
        if (!newOptions.includes(randomItem)) {
          newOptions.push(randomItem);
        }
      }
      
      // Shuffle the options
      newOptions.sort(() => Math.random() - 0.5);
      setOptions(newOptions);
      setSelectedOptions([]);
      setIsVerified(false);
      setIsRefreshing(false);
      
      if (onValidate) {
        onValidate(false);
      }
    }, 300);
  };

  useEffect(() => {
    generateCaptcha();
  }, []);

  const handleOptionClick = (option) => {
    if (isVerified || isRefreshing) return;
    
    const newSelectedOptions = [...selectedOptions];
    const optionIndex = newSelectedOptions.indexOf(option);
    
    if (optionIndex === -1) {
      // Add to selected options
      newSelectedOptions.push(option);
    } else {
      // Remove from selected options
      newSelectedOptions.splice(optionIndex, 1);
    }
    
    setSelectedOptions(newSelectedOptions);
  };
  
  const handleVerify = () => {
    if (selectedOptions.length === 0) return;
    
    // Check if all selected options are from the target category
    const targetItems = itemCategories[targetCategory];
    const allCorrect = selectedOptions.every(option => targetItems.includes(option));
    
    // Check if all target items are selected
    const allTargetItemsSelected = options
      .filter(option => targetItems.includes(option))
      .every(option => selectedOptions.includes(option));
    
    const verified = allCorrect && allTargetItemsSelected;
    setIsVerified(verified);
    setShowFeedback(true);
    
    if (onValidate) {
      onValidate(verified);
    }
  };

  const handleRefresh = () => {
    generateCaptcha();
  };

  // Get current language
  const currentLang = localStorage.getItem('i18nextLng') || 'en';
  
  // Get category name in current language with fallback
  const getCategoryName = () => {
    if (!targetCategory || !categoryNames[targetCategory]) {
      return currentLang === 'zh' ? '图片' : 'images';
    }
    return categoryNames[targetCategory][currentLang] || categoryNames[targetCategory].en;
  };
  
  const categoryName = getCategoryName();

  return (
    <div className="image-captcha-container">
      <div className="captcha-question">
        {currentLang === 'zh' ? '请点击所有的' : 'Click all'} <span className="target-category">{categoryName}</span> {currentLang === 'zh' ? '图标' : 'icons'}
      </div>
      <div className={`captcha-options ${isRefreshing ? 'refreshing' : ''} ${selectedOptions.length > 0 ? 'has-selections' : ''}`}>
        {options.map((option, index) => (
          <button
            key={index}
            className={`captcha-option ${selectedOptions.includes(option) ? 'selected' : ''}`}
            onClick={() => handleOptionClick(option)}
            disabled={isVerified || isRefreshing}
            type="button"
          >
            <span className="option-emoji">{option}</span>
          </button>
        ))}
      </div>
      <div className="captcha-actions">
        <button
          type="button"
          className="captcha-verify-btn"
          onClick={handleVerify}
          disabled={selectedOptions.length === 0 || isVerified || isRefreshing}
        >
          {currentLang === 'zh' ? '验证' : 'Verify'}
        </button>
        <button
          type="button"
          className="captcha-refresh-btn"
          onClick={handleRefresh}
          title={t('captcha.refresh')}
          disabled={isRefreshing}
        >
          🔄 {currentLang === 'zh' ? '刷新' : 'Refresh'}
        </button>
      </div>
      {showFeedback && (
        <div className={`captcha-feedback ${isVerified ? 'success' : 'error'}`}>
          {isVerified ? (currentLang === 'zh' ? '✓ 验证成功' : '✓ Verification successful') : (currentLang === 'zh' ? '✗ 请再试一次' : '✗ Please try again')}
        </div>
      )}
      {error && (
        <span className="error-message">{error}</span>
      )}
    </div>
  );
};

export default ImageCaptcha;